const jwt = require("jsonwebtoken");
const Wxa = require("./../../../../lib/wxa/wxa.class");

module.exports = class extends doodoo.Controller {
    async _initialize() {
        await this.isWxaAuth();
    }

    /**
     *
     * @api {get} /api/base/getWxaInfo 获取小程序信息
     * @apiDescription 获取小程序信息
     * @apiGroup App Api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Referer 小程序referer
     *
     * @apiSampleRequest /api/base/getWxaInfo
     */
    async getWxaInfo() {
        this.success(this.state.wxa);
    }

    /**
     *
     * @api {get} /api/base/getWxaAuditInfo 获取小程序审核信息
     * @apiDescription 获取小程序审核信息
     * @apiGroup App Api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Referer 小程序referer
     *
     * @apiSampleRequest /api/base/getWxaAuditInfo
     */
    async getWxaAuditInfo() {
        const audit = await this.model("wxa_audit")
            .query({
                where: {
                    wxa_id: this.state.wxa.id
                }
            })
            .fetch();
        this.success(audit);
    }

    /**
     *
     * @api {get} /api/base/getWxaQrcode 获取小程序码
     * @apiDescription 获取小程序码
     * @apiGroup App Api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Referer 小程序referer
     *
     * @apiParam {String} scene 场景值
     * @apiParam {String} page 小程序跳转路径
     *
     * @apiSampleRequest /api/base/getWxaQrcode
     */
    async getWxaQrcode() {
        const { scene = "welcome", page } = this.query;
        this.ctx.set(
            "Content-disposition",
            `attachment; filename=${this.state.wxa.user_name}.jpg`
        );

        const wxa = new Wxa(process.env.OPEN_APPID, process.env.OPEN_APPSECRET);
        this.state.wxa = await this.checkWxaAuthorizerAccessToken(
            this.state.wxa
        );
        this.body = wxa.getWxaQrcodeUnlimit(
            this.state.wxa.authorizer_access_token,
            scene,
            page
        );
    }

    async getWxaPathQrcode() {
        const { path, width, type } = this.query;
        const wxa = await this.isWxaAuth();
        if (wxa) {
            const wxaObj = new Wxa(
                process.env.OPEN_APPID,
                process.env.OPEN_APPSECRET
            );
            const wxa = await this.checkWxaAuthorizerAccessToken(
                this.state.wxa
            );

            this.body = wxaObj.getWxaQrcode(
                wxa.authorizer_access_token,
                path,
                width,
                type
            );
        }
    }

    async isUserAuth() {
        try {
            const Token = this.query.Token || this.get("Token");
            if (!Token) {
                this.status = 401;
                this.fail("授权失败", "User Unauthorized");
                return false;
            }

            const decoded = jwt.verify(Token, process.env.JWT_SECRET);
            const user = await this.model("user")
                .query({ where: { id: decoded.id } })
                .fetch();
            if (!user) {
                this.status = 401;
                this.fail("用户被禁用", "User Unauthorized");
                return false;
            }
            this.hook.run("wxaAnalysisUser", user.wxa_id, user.id);
            return (this.state.user = user);
        } catch (err) {
            this.status = 401;
            this.fail("授权失败", "User Unauthorized");
            return false;
        }
    }

    async isWxaAuth() {
        try {
            // const referer = this.get("Referer");
            // const referers = referer.substr(26).split("/");
            // const WxaAppId = referers[0];

            const referer = this.query.Referer || this.get("Referer");
            const reg = new RegExp("https://servicewechat.com/(\\w*)/(\\w*)/");
            if (!referer.match(reg)) {
                console.log("Referer有误", "Referer Unknow");
                this.status = 500;
                this.fail("Referer有误", "Referer Unknow");
                return false;
            }

            const WxaAppId = RegExp.$1;
            if (!WxaAppId) {
                this.status = 401;
                this.fail("授权失败", "Wxa Unauthorized");
                return false;
            }

            const wxa = await this.model("wxa")
                .query({
                    where: {
                        authorizer_appid: WxaAppId
                    }
                })
                .fetch();
            if (!wxa) {
                this.status = 401;
                this.fail("小程序未授权", "Wxa Unauthorized");
                return false;
            }
            if (!wxa.authorized) {
                this.status = 401;
                this.fail("小程序已取消授权", "Wxa Has Been Unauthorized");
                return false;
            }
            if (!wxa.status) {
                this.status = 401;
                this.fail("小程序被禁用", "Wxa Status Unauthorized");
                return false;
            }

            return (this.state.wxa = wxa);
        } catch (err) {
            this.status = 401;
            this.fail("授权失败", "Wxa Unauthorized");
            return false;
        }
    }
};
